package com.goldenlight.fvms.manager.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.goldenlight.fvms.manager.entity.EmployFreeApply;
import com.goldenlight.fvms.manager.excelentity.EmployCountExcelEntity;
import com.goldenlight.fvms.manager.service.EmployFreeApplyService;
import com.goldenlight.fvms.manager.service.ProductFreeApplyService;
import com.goldenlight.fvms.manager.utils.ExcelUtils;
import com.goldenlight.fvms.manager.utils.GlobalCont;
import com.goldenlight.fvms.manager.vo.DeleteVO;
import com.goldenlight.fvms.manager.vo.Request;
import com.goldenlight.fvms.manager.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工通行车辆申请信息表 前端控制器
 * </p>
 *
 * @author luocx
 * @since 2018-12-08
 */
@Api("员工通行车辆申请信息 API")
@RestController
@RequestMapping("/employFreeApply")
public class EmployFreeApplyController {
    private Logger logger = LoggerFactory.getLogger(ProductFreeApplyController.class);
    @Autowired
    private EmployFreeApplyService employFreeApplyService;
    @Autowired
    private ProductFreeApplyService productFreeApplyService;

    @DeleteMapping("delete")
    public Response delete(@RequestBody DeleteVO deleteVO) {
        logger.info("request:{}", deleteVO);
        int delete = 0;
        if(deleteVO.getSelectType()==5){
            employFreeApplyService.delete(deleteVO.getBuildVersion());
        }else {
            productFreeApplyService.delete(deleteVO.getBuildVersion());
        }
        return Response.build(200, GlobalCont.SUCCESS, delete);
    }


    @ApiOperation(value = "根据employFreeApply查询信息", notes = "查询列表")
    @PostMapping("/getListByPage")
    public Response getListByPage(@RequestBody Request<EmployFreeApply> request) {

        EmployFreeApply employFreeApply = request.getData();
        Page page = request.getPage();
        QueryWrapper<EmployFreeApply> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(employFreeApply.getCarNum())) {
            wrapper.lambda().like(EmployFreeApply::getCarNum, employFreeApply.getCarNum());
        }
        if (!StringUtils.isEmpty(employFreeApply.getApplicantName())) {
            wrapper.lambda().like(EmployFreeApply::getApplicantName, employFreeApply.getApplicantName());
        }
        if (!StringUtils.isEmpty(employFreeApply.getApplicantUnit())) {
            wrapper.lambda().like(EmployFreeApply::getApplicantUnit, employFreeApply.getApplicantUnit());
        }
        if (!StringUtils.isEmpty(employFreeApply.getCarBussType())) {
            wrapper.lambda().like(EmployFreeApply::getCarBussType, employFreeApply.getCarBussType());
        }
        if (null != employFreeApply.getBuildVersion()) {
            wrapper.lambda().eq(EmployFreeApply::getBuildVersion, employFreeApply.getBuildVersion());
        }
        if (null != employFreeApply.getTimeStamp()) {
            wrapper.lambda().and(e -> e.gt(EmployFreeApply::getTimeStamp, employFreeApply.getTimeStamp()));
            Calendar c = Calendar.getInstance();
            c.setTime(employFreeApply.getTimeStamp());
            c.add(Calendar.DAY_OF_MONTH, 1);
            wrapper.lambda().and(e -> e.lt(EmployFreeApply::getTimeStamp, c.getTime()));
        }
        wrapper.orderByDesc("build_version");
        IPage employFreeApplies = employFreeApplyService.page(page, wrapper);
        return Response.build(200, GlobalCont.SUCCESS, employFreeApplies);
    }

    @ApiOperation(value = "根据employFreeApply查询信息", notes = "查询列表")
    @PostMapping("/getList")
    public Response getList(@ModelAttribute EmployFreeApply employFreeApply) {
        logger.info("employFreeApply:{}", employFreeApply);
        QueryWrapper<EmployFreeApply> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(employFreeApply.getCarNum())) {
            wrapper.lambda().like(EmployFreeApply::getCarNum, employFreeApply.getCarNum());
        }
        if (!StringUtils.isEmpty(employFreeApply.getApplicantName())) {
            wrapper.lambda().like(EmployFreeApply::getApplicantName, employFreeApply.getApplicantName());
        }
        if (!StringUtils.isEmpty(employFreeApply.getApplicantUnit())) {
            wrapper.lambda().like(EmployFreeApply::getApplicantUnit, employFreeApply.getApplicantUnit());
        }
        if (!StringUtils.isEmpty(employFreeApply.getCarBussType())) {
            wrapper.lambda().like(EmployFreeApply::getCarBussType, employFreeApply.getCarBussType());
        }
        if (null != employFreeApply.getBuildVersion()) {
            wrapper.lambda().eq(EmployFreeApply::getBuildVersion, employFreeApply.getBuildVersion());
        }
        if (null != employFreeApply.getTimeStamp()) {
            wrapper.lambda().and(e -> e.gt(EmployFreeApply::getTimeStamp, employFreeApply.getTimeStamp()));
            Calendar c = Calendar.getInstance();
            c.setTime(employFreeApply.getTimeStamp());
            c.add(Calendar.DAY_OF_MONTH, 1);
            wrapper.lambda().and(e -> e.lt(EmployFreeApply::getTimeStamp, c.getTime()));
        }
        wrapper.orderByDesc("build_version");
        List<EmployFreeApply> employFreeApplies = employFreeApplyService.list(wrapper);
        return Response.build(200, GlobalCont.SUCCESS, employFreeApplies);
    }

    @ApiOperation(value = "根据employFreeApply导出excel", notes = "导出excel")
    @PostMapping("/exportExcel")
    public void exportExcel(@ModelAttribute EmployFreeApply employFreeApply, HttpServletResponse response) {
        List<EmployFreeApply> list = (List<EmployFreeApply>) this.getList(employFreeApply).getData();
        ExcelUtils.exportExcel(list, "集团公司员工通勤车辆免费通行批准明细单（区间）", "sheet1",
                EmployFreeApply.class, "导出信息.xlsx", true, response);
    }

    @ApiOperation(value = "根据employFreeApply更新信息", notes = "更新数据库")
    @PostMapping("/updateEmployFreeApply")
    public Response updateRecord(@ModelAttribute EmployFreeApply employFreeApply) {
        logger.info("employFreeApply:{}", employFreeApply);
        Wrapper<EmployFreeApply> wrapper = new UpdateWrapper<>();
        ((UpdateWrapper<EmployFreeApply>) wrapper).eq("CAR_NUM", employFreeApply.getCarNum()).eq("APPLICANT_NAME", employFreeApply.getApplicantName());
        boolean result = employFreeApplyService.update(employFreeApply, wrapper);
        if (result) {
            return Response.build(000, "更新成功", null);
        } else {
            return Response.build(200, "更新失败", null);
        }
    }

    @ApiOperation(value = "根据productFreeApply更新信息", notes = "更新数据库")
    @PostMapping("/Statistics")
    public Response statistics(@RequestBody Request<EmployFreeApply> request) {
        logger.info("request:{}", request);
        logger.info("page:{}", request.getPage().getCurrent());

        EmployFreeApply employFreeApply = request.getData();
        Page page = request.getPage();
        QueryWrapper<EmployFreeApply> wrapper = getEmployFreeApplyQueryWrapper(employFreeApply);
        IPage result = employFreeApplyService.page(page, wrapper);
        return Response.build(200, GlobalCont.SUCCESS, result);
    }

    private QueryWrapper<EmployFreeApply> getEmployFreeApplyQueryWrapper(EmployFreeApply employFreeApply) {
        QueryWrapper<EmployFreeApply> wrapper = new QueryWrapper<>();
        wrapper.select("APPLICANT_UNIT", "BUILD_VERSION", "count(1) count", "car_buss_type");

        if (!StringUtils.isEmpty(employFreeApply.getApplicantUnit())) {
            wrapper.lambda().like(EmployFreeApply::getApplicantUnit, employFreeApply.getApplicantUnit());
        }


        if (null != employFreeApply.getBuildVersion()) {
            wrapper.lambda().eq(EmployFreeApply::getBuildVersion, employFreeApply.getBuildVersion());
        }
        wrapper.lambda()
                .groupBy(EmployFreeApply::getCarBussType, EmployFreeApply::getBuildVersion)
                .orderByDesc(EmployFreeApply::getBuildVersion);
        return wrapper;
    }

    @ApiOperation(value = "根据productFreeApply导出excel", notes = "导出excel")
    @PostMapping("/exportExcelCount")
    public void exportExcelCount(@RequestBody Request<EmployFreeApply> request, HttpServletResponse response) {
        EmployFreeApply employFreeApply = request.getData();
        QueryWrapper<EmployFreeApply> wrapper = getEmployFreeApplyQueryWrapper(employFreeApply);
        List<EmployFreeApply> list = employFreeApplyService.list(wrapper);
        List<EmployCountExcelEntity> employCountExcelEntities = list.parallelStream().map(item -> EmployCountExcelEntity.builder()
                .applicantUnit(item.getApplicantUnit()).carBussType(item.getCarBussType()).buildVersion(item.getBuildVersion())
                .count(item.getCount()).build())
                .collect(Collectors.toList());
        logger.info("employCountExcelEntities:{}", employCountExcelEntities);

        ExcelUtils.exportExcel(employCountExcelEntities, "集团公司员工通勤车辆免费通行批准汇总信息（区间）", "sheet1",
                EmployCountExcelEntity.class, "导出信息.xlsx", true, response);
    }

}

